package org.dingfugui.triple.context;

import org.dingfugui.triple.link.Link;
import org.dingfugui.triple.link.SimplePoolDirectLink;
import org.dingfugui.triple.protocol.Protocol;
import org.dingfugui.triple.protocol.binary.aio.AioProtocol;
import org.dingfugui.triple.protocol.binary.aio.AioProxyHandler;
import org.dingfugui.triple.proxy.ProxyFactory;
import org.dingfugui.triple.proxy.ProxyHandler;
import org.dingfugui.triple.proxy.jdk.JdkProxyFactory;

import java.io.IOException;

/**
 * Created by fugui.ding on 2015/6/11.
 */
public class DefaultConsumerContext implements ConsumerContext {

    /* 远程调用代理工厂 */
    protected ProxyFactory proxyFactory = new JdkProxyFactory();
    /* 远程服务协议 */
    protected Protocol protocol;
    /* 远程连接方式 */
    protected Link link;

    public DefaultConsumerContext(String host) {
        this.protocol = new AioProtocol(host);
        this.link = new SimplePoolDirectLink(host, protocol.getConnectionFactory());
    }

    public DefaultConsumerContext(String host, int port) {
        this.protocol = new AioProtocol(host, port);
        this.link = new SimplePoolDirectLink(host, port, protocol.getConnectionFactory());
    }

    public <T> T buildConsumer(Class<T> service) {
        ProxyHandler handler = new AioProxyHandler(link, protocol.getTranslator());
        return proxyFactory.getProxy(service, handler);
    }

    public void close() throws IOException {
        link.close();
    }

}
